package cc.beup.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * @Author: Byron Bai
 * @Date: 2021/4/18 20:10
 * @Description:
 */
public class UniqueNoUtil {

    private UniqueNoUtil() {
    }

    /**
     * 获取uuid，去掉-的
     *
     * @Author: Byron Bai
     * @Date: 2021/4/18 20:10
     */
    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-", "");
    }

    /**
     * 生成32位的交易编号
     * 测试3秒生成一百万的编号不重复。
     *
     * @Author: Byron Bai
     * @Date: 2021/4/18 20:10
     */
    public static String getTradeNo32() {
        int tradeNoLength = 32;
        //两次uuid的hash保证不重复
        int hashCode1 = getUUID().hashCode();
        if (hashCode1 < 0) {
            hashCode1 = -hashCode1;
        }
        int hashCode2 = getUUID().hashCode();
        if (hashCode2 < 0) {
            hashCode2 = -hashCode2;
        }
        //再加上当前时间戳，进一步避免重复
        String currentTimeStr = String.valueOf(System.currentTimeMillis());
        String payNo = currentTimeStr + hashCode1 + hashCode2;
        //补全长度/去除多余位数
        if (payNo.length() < tradeNoLength) {
            payNo = StringUtils.rightPad(payNo, tradeNoLength, "0");
        }
        if (payNo.length() > tradeNoLength) {
            payNo = payNo.substring(0, tradeNoLength);
        }
        return payNo;
    }

    public static void main(String[] args) {
        long l = System.currentTimeMillis();
        Set<String> set = new HashSet<>();
        for (int i = 0; i < 1000000; i++) {
            String payNo = getTradeNo32();
            set.add(payNo);
        }
        long l2 = System.currentTimeMillis();
        System.out.println((l2 - l) + "ms");
        System.out.println(set.size());
    }

}
